package com.chat.socketservice;

import com.chat.room.Room;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by shirenchuang on 2017/4/3.
 */
public class ThreadSocket implements Runnable {
    private Socket socket;
    private ConcurrentHashMap<Integer,Room> socketmap  =  new ConcurrentHashMap<Integer,Room>();

    public ThreadSocket(Socket socket){
        this.socket = socket;
    }
    public ThreadSocket(ConcurrentHashMap<Integer,Room> socketmap , Socket socketcurr){
        this.socketmap = socketmap;
        this.socket = socketcurr;
    }
    private InputStream is;
    @Override
    public void run() {

        try {

           while(true){
               is = socket.getInputStream();
               byte[] b = new byte[1024];
               int length = is.read(b);
               String message = new String(b,0,length);
               //解析房间号
               String[] res = message.split("|");
               //0:进入房间  1 ：说话
               Integer type = Integer.parseInt(res[0]);
               Integer roomid = Integer.parseInt(res[1]);
               if(type==0) {
                   socketmap.get(roomid).getSockets().add(socket);
               }
               Room room = socketmap.get(roomid);
               String msg = res[2];
               System.out.println(Thread.currentThread().getName()+":"+msg);

               for(Socket socket :room.getSockets()){
                   OutputStream os = socket.getOutputStream();
                   os.write(message.getBytes());
                   os.flush();
               }
           }





        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
